/**
* @author  sparkHou
* @date 2020-04-28 13:54
* @Description:
*/
<template>
  <div class="cmsPopoverTree">
    <el-popover
        :disabled="disabled"
        placement="top"
       style="min-width: 400px"
        @show="showHandle"
        trigger="click">
      <div class="popover WholeScroll">
        <el-input size="small"
                  placeholder="请搜索"
                  v-model="filterVal"
                  class="treeInput"/>
        <el-tree
            :data="data"
            show-checkbox
            node-key="id"
            ref="tree"
            @check="nodeClick"
            :filter-node-method="filterNode"
            :props="defaultProps">
        </el-tree>
      </div>
      <el-button style="width: 100%" slot="reference" class="treeButton" :disabled="disabled">
        <div class="showTree">
          <el-tag size="mini"
                  :key="index"
                  closable
                  v-for="(item,index) in selectVal"
                  @close="handleClose(index)">
            {{item.name}}
          </el-tag>
        </div>
      </el-button>
    </el-popover>
  </div>
</template>

<script>
var ergodicNum = 0;
  export default {
    name: "cmsPopoverTree",
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      data: {
        type: Array,
          default:()=>[]
      },
      selectVal: {
        type: Array,
          default:()=>[]
      },
      defaultProps: {
        type: Object,
        default: {
          children: 'children',
          label: 'name'
        }
      },
      type: {
        type: String,
        default: 'single'
      }//切换选择模式：single--单选，multi--多选，onlyOne--只能选一个
    },
    watch: {
      'filterVal': {
        handler(val) {
          this.$refs.tree.filter(val);
        }
      },
      'selectVal':{
        handler(val) {
          this.updateTree()
            this.dealTreeData()

        }
      },

    },
    data() {
      return {
        filterVal: '',
      }
    },
      mounted(){
      this.dealTreeData()
      },
    methods: {
        //处理树的data
        dealTreeData(){
            this.data.forEach((item,index)=>{
                this.ergodic(item,(e)=>{
                    console.log(e)
                    if(!!e.checked){
                        e.disabled = true
                    }
                    /*
                    for(let i in this.selectVal){
                        console.log()
                        if(this.selectVal[i].id == e.id){
                        }
                    }*/
                })
            })

        },
        ergodic(item, callback) {
            let findItem = []
            if (item.hasOwnProperty('children') && item.children.length > 0) {
                findItem = item.children
                ergodicNum++
                this.ergodic(findItem[0], callback)
            } else {
                callback && callback(item,ergodicNum)
            }
        },
        setTreeData(val){
            console.log(val)
            this.$nextTick(()=>{
                let idArr = []
                val.forEach(item => {
                    idArr.push(item.id)
                })
                this.$refs.tree.setCheckedKeys(idArr)
                this.$refs.tree.$forceUpdate()


              /*  let that = this
                setTimeout(function() {
                    val.forEach(value => {
                        console.log(value)
                        console.log(that.$refs.tree)
                        that.$refs.tree.setChecked(value, true, false);
                    });
                }, 500);*/
            })
        },
      /**
       * 删除tag
       * @param i
       */
      handleClose(index) {
        if (this.disabled) {
          return
        }
        this.$emit('delTag', index)
        //this.selectVal.splice(index, 1)
        this.updateTree()
      },
      /**
       * 节点点击
       * @param checkedNodes
       * @param tree
       */
      nodeClick(checkedNodes, tree) {
          console.log(checkedNodes,'======',tree,this.type )
        if (this.type === 'multi') {
          let arr = []
          tree.checkedNodes.forEach(item => {
            if (item.treeLevel === 2) {
              arr.push(item)
            }
          })
          this.$emit('addMulTag', arr)
          this.updateTree()
          return;
        }
        if (this.type === 'onlyOne') {
          if (checkedNodes.treeLevel === 1){
            this.$emit('addOnlyTag', [checkedNodes.children[0]])
            this.updateTree()
            return
          }
          this.$emit('addOnlyTag', [checkedNodes])
          this.updateTree()
          return
        }
        // 添加点击的节点(节点为1时只添加1个子节点)
        if (checkedNodes.treeLevel === 1) {
          console.log('1')
          //选中列表中没有此父级点子节点，选中第一个
          //如果又选中的子节点，点击父节点无效
          if (JSON.stringify(this.selectVal).indexOf(`"name":"${checkedNodes.name}"`) === -1) {
            console.log('2')
            let flag = true
            this.selectVal.forEach(item => {
              checkedNodes.children.forEach(chil=>{
                if (item.id === chil.id) {
                  flag = false
                }
              })
            })
            if (flag) {
                console.log(checkedNodes.children[0],'11111111111')
              this.$emit('addTag', checkedNodes.children[0])
              //this.selectVal.push(checkedNodes.children[0])
            }
          }
        }
        // 当点击子节点时
        if (checkedNodes.treeLevel === 2) {
          console.log('3')
          //所选节点以选中时，取消选中
          if (tree.checkedKeys.indexOf(checkedNodes.id) === -1) {
            console.log('4')
            this.selectVal.forEach((item, index) => {
              if (item.id === checkedNodes.id) {
                this.$emit('delTag', index)
                //this.selectVal.splice(index, 1)
              }
            })
            return
          }
          // 存在同一级点子节点时，去除子节点，添加选中点新节点
          if (JSON.stringify(this.selectVal).indexOf(`"name":"${checkedNodes.name.split('-')[0]}`) !== -1) {
            this.selectVal.forEach((item, index) => {
              if (item.name.split('-')[0] === checkedNodes.name.split('-')[0]) {
                console.log(item.name.split('-')[0] ,checkedNodes.name.split('-')[0])
                this.$emit('delTag', index)
                //this.s(index, 1)
                  console.log(checkedNodes,'222222222222')
                this.$emit('addTag', checkedNodes)
                //this.selectVal.push(checkedNodes)
              }
            })

          } else {
              console.log(checkedNodes,'33333333')
            this.$emit('addTag', checkedNodes)
            //this.selectVal.push(checkedNodes)

          }
        }
        this.updateTree()
      },
      /**
       * 筛选
       * @param value
       * @param data
       * @returns {boolean}
       */
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      /**
       * 更新树
       */
      updateTree() {
        let idArr = []
        this.selectVal.forEach(item => {
          idArr.push(item.id)
        })
        this.$refs.tree.setCheckedKeys(idArr)
        this.$refs.tree.$forceUpdate()
      },
      /**
       * 重置树
       */
      reset() {
        this.$refs.tree.setCheckedKeys([]);
      },
      /**
       * 显示前更新组件
       */
      showHandle() {
          console.log('44444444444444')
        this.updateTree()
      },
      // ----------------------------父组件方法使用示例
      /**
       *  -----@addMulTag="addMulTag"
       * 多选增加--多选模式使用
       * @param val
       */
      addMulTag(val) {
        console.log(val)
        this.formBaseData.hqDeptUsers.splice(0, this.formBaseData.hqDeptUsers.length)
        val.forEach(item => {
          this.formBaseData.hqDeptUsers.push(item)
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .cmsPopoverTree {
    .treeButton {
      width: 96%;
      min-height: 32px;

      .showTree {
        display: flex;
        flex-wrap: wrap;
        align-items: center;

        .el-tag {
          margin-right: 10px;
          margin-bottom: 10px;
        }
      }
    }
  }
</style>
